﻿using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.Common.Models;
using wt.wine.Domain.Entities;

namespace wt.wine.Application.ManageConfigtable.Command
{
    public class AddConfigTableRepository : IRequest<Json<string>>
    {
        /// <summary>
        /// 类型：1、确酒提醒配置
        /// </summary>
        public int type { get; set; }
        /// <summary>
        /// 通用预警容量 单位：ml
        /// </summary>
        public int capacitythreshold { get; set; }
    }

    public class AddConfigTableRepositoryHandler : IRequestHandler<AddConfigTableRepository, Json<string>>
    {
        private readonly ICurrentUserService _icurrentUserServices;
        private readonly IConfigtableRepository _iconfigtabelRepository;
        public AddConfigTableRepositoryHandler(ICurrentUserService icurrentUserServices, IConfigtableRepository iconfigtabelRepository)
        {
            _icurrentUserServices = icurrentUserServices;
            _iconfigtabelRepository = iconfigtabelRepository;
        }
        public async Task<Json<string>> Handle(AddConfigTableRepository request, CancellationToken cancellationToken)
        {
            if (request.type != 1)
            {
                return Json<string>.Failed("请选择对应的类型", "");
            }
            else if (request.type == 1 && request.capacitythreshold < 300)
            {
                return Json<string>.Failed("预警容量需要大于300", "");
            }
            else
            {
                int userid = _icurrentUserServices.GetUserId();
                if ((await _iconfigtabelRepository.GetTypeCountByUserId(userid, request.type, cancellationToken)) > 0)
                {
                    return Json<string>.Failed("当前配置已经存在，请修改", "");
                }
                else
                {
                    configtable model = new configtable()
                    {
                        binduserid = userid,
                        userid = userid,
                        type = request.type,
                        capacitythreshold = request.capacitythreshold,
                        createtime = DateTime.Now,
                        remark = "",
                        state = 0,
                        updatetime = DateTime.Now,
                        userpid = userid
                    };
                    await _iconfigtabelRepository.AddConfigTable(model, cancellationToken);
                    return Json<string>.Success("添加成功", "");
                }
            }
        }
    }
}
